package com.lizhi.dingdong.apk.service

import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSession
import javax.net.ssl.X509TrustManager

class WebSocketConnector(private val webSocketListener: WebSocketListener = SimpleWebSocketListener()) {

    private val WEBSOCKET_URL =
        "wss://192.168.1.10:8443/ws?apiKey=your_static_api_key&secret=your_static_api_secret" // 替换成您的 WebSocket 地址
    private val NOTIFICATION_ID = 8443
    private var client: OkHttpClient? = null

    private var webSocketClient: WebSocket? = null

    fun initWebSocket() {
        // ⚠️ 警告：此 TrustManager 信任所有证书，包括自签名证书。
        // 这种做法在生产环境中极不安全，因为它使得应用容易受到中间人攻击 (MITM)。
        // 仅在本地开发和测试自签名证书时使用。
        val trustAllCerts = arrayOf<X509TrustManager>(object : X509TrustManager {
            override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}

            // 关键：对服务器证书不执行任何检查
            override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {}

            override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
        })


        // 初始化 SSLContext
        val sslContext = try {
            val sslContext = SSLContext.getInstance("SSL")
            sslContext.init(null, trustAllCerts, SecureRandom())
            sslContext
        } catch (e: Exception) {
    //        Log.e("WebSocketService", "Failed to initialize SSLContext for WSS", e)
            print("Failed to initialize SSLContext for WSS")
            return // 初始化失败，无法继续连接
        }

        client = OkHttpClient.Builder()
            // 信任所有证书的关键设置
            .sslSocketFactory(sslContext.socketFactory, trustAllCerts[0])
            // 2. 忽略主机名验证（因为您使用了 IP 地址 127.0.0.1，证书通常是针对域名签发的）
            .hostnameVerifier(object : HostnameVerifier {
                override fun verify(hostname: String?, session: SSLSession?): Boolean {
                    // ⚠️ 总是返回 true，跳过主机名检查，仅用于开发测试
                    return true
                }
            })
            .build()
    }

    fun connectServer() {

        val request = Request.Builder().url(WEBSOCKET_URL).build()

        if (client == null) {
            return
        }

        webSocketClient = client!!.newWebSocket(request, this.webSocketListener)
    }

    fun close(){
        webSocketClient?.close(1000, "Service Destroyed")
    }

    open class SimpleWebSocketListener :
        WebSocketListener() {

        override fun onOpen(webSocket: WebSocket, response: Response) {
            println("Connection Opened: WSS")
            // 连接成功后，可以发送订阅请求 (如果服务器需要)
            webSocket.send("SUBSCRIBE_TO_NOTIFICATIONS")
        }

        override fun onMessage(webSocket: WebSocket, text: String) {
            println("Received message: $text")
        }

        override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
            print("WebSocket is closing:")
            webSocket.close(1000, "client close") // 客户端发起关闭
        }

        override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
            println("Connection closed")
        }

        override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
            println("WebSocket connection failed: ${t.message} (Will attempt to reconnect)")
            println(t)
        }
    }
}

fun main() = runBlocking{
    val connector = WebSocketConnector(WebSocketConnector.SimpleWebSocketListener())

    connector.initWebSocket()
    connector.connectServer()

    delay(10000000)
    connector.close()
}